package ast.nodes.commandNodes;

import scanner.Token;
import ast.ASTNode;
import ast.Evaluation;
import ast.nodes.CommandNode;
import ast.nodes.ParameterNode;

public class InsertNode extends CommandNode {

	public InsertNode() {
		super();
	}
	
	public InsertNode(Token data) {
		super(data);
	}
	
    /**
     * insert(x,str) inserts a string 'str' before index x. If x is 
     * greater than EOL, the string should simply be inserted at the
     * end of LINE.
     */
    @Override
    public void run(Evaluation input) {
    	Integer i = null;
    	String s = null;
    	for(ASTNode child : children)
    	{
			switch(child.getData().getType())
			{
				case CHARACTER:
					if(s== null)
						s = "" + child.getData().getTokenString().charAt(0);
					break;
				case QUOTED_STRING:
					if(s== null)
					{
						s = child.getData().getTokenString();
						s = s.substring(1, s.length()-1);
					}
					break;
				case INTEGER:
					if(i==null)
						i = Integer.parseInt(child.getData().getTokenString());
					break;
				case EOL:
					if(i==null)
						i = input.length();
					break;
			}
    	}
    	if(i!=null && s!=null)
    	{
    		input.insert(i, s);
    	}
    }
}